// pages/detail/detail.js
const app = getApp()

Page({
  data: {
    productId: null,
    product: {},
    selectedSpec: null,
    quantity: 1,
    loading: false,
    cartCount: 0,
    imageUrls: []
  },

  onLoad(options) {
    const { id } = options
    if (id) {
      this.setData({ productId: id })
      this.loadProductDetail()
    }
  },

  onShow() {
    // 更新购物车数量
    this.setData({
      cartCount: app.globalData.cartCount
    })
  },

  onShareAppMessage() {
    return {
      title: this.data.product.name || '精美鲜花',
      path: `/pages/detail/detail?id=${this.data.productId}`,
      imageUrl: this.data.product.main_image
    }
  },

  // 加载商品详情
  async loadProductDetail() {
    if (!this.data.productId) return

    this.setData({ loading: true })

    try {
      const response = await app.request({
        url: `/flowers/${this.data.productId}/`
      })

      if (response.success) {
        const product = response.data
        
        // 处理图片数组
        const imageUrls = product.images ? product.images.map(img => img.image_url) : []
        
        // 如果有规格，默认选择第一个
        let selectedSpec = null
        if (product.specs && product.specs.length > 0) {
          selectedSpec = product.specs[0]
        }

        this.setData({
          product,
          selectedSpec,
          imageUrls
        })

        // 设置页面标题
        wx.setNavigationBarTitle({
          title: product.name
        })
      } else {
        app.showToast(response.message || '加载失败', 'none')
      }
    } catch (error) {
      console.error('加载商品详情失败:', error)
      app.showToast('加载失败，请重试', 'none')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 图片点击预览
  onImageTap(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current: urls[current]
    })
  },

  // 规格选择
  onSpecTap(e) {
    const spec = e.currentTarget.dataset.spec
    this.setData({
      selectedSpec: spec,
      quantity: 1 // 重置数量
    })
  },

  // 数量变更
  onQuantityChange(e) {
    const type = e.currentTarget.dataset.type
    let { quantity } = this.data
    const maxStock = this.getMaxStock()

    if (type === 'minus' && quantity > 1) {
      quantity--
    } else if (type === 'plus' && quantity < maxStock) {
      quantity++
    }

    this.setData({ quantity })
  },

  // 数量输入
  onQuantityInput(e) {
    let quantity = parseInt(e.detail.value) || 1
    const maxStock = this.getMaxStock()

    if (quantity < 1) quantity = 1
    if (quantity > maxStock) quantity = maxStock

    this.setData({ quantity })
  },

  // 获取最大库存
  getMaxStock() {
    const { product, selectedSpec } = this.data
    if (selectedSpec) {
      return selectedSpec.stock
    }
    return product.stock || 0
  },

  // 获取当前价格
  getCurrentPrice() {
    const { product, selectedSpec } = this.data
    if (selectedSpec) {
      return selectedSpec.price
    }
    return product.price || 0
  },

  // 客服点击
  onContactTap() {
    wx.showModal({
      title: '联系客服',
      content: '请添加微信客服：huaxianguan2024',
      showCancel: false
    })
  },

  // 购物车点击
  onCartTap() {
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },

  // 加入购物车
  async onAddToCart() {
    if (!app.globalData.token) {
      this.showLoginModal()
      return
    }

    const { product, selectedSpec, quantity } = this.data

    // 检查库存
    const maxStock = this.getMaxStock()
    if (maxStock <= 0) {
      app.showToast('商品已售罄', 'none')
      return
    }

    if (quantity > maxStock) {
      app.showToast('库存不足', 'none')
      return
    }

    app.showLoading('添加中...')

    try {
      const response = await app.request({
        url: '/orders/cart/',
        method: 'POST',
        data: {
          flower: product.id,
          flower_spec: selectedSpec ? selectedSpec.id : null,
          quantity
        }
      })

      if (response.success) {
        app.showToast('已加入购物车')
        
        // 更新购物车数量
        app.getCartCount()
        
        // 显示购物车提示
        this.showCartTip()
      } else {
        app.showToast(response.message || '添加失败', 'none')
      }
    } catch (error) {
      console.error('加入购物车失败:', error)
      app.showToast('添加失败，请重试', 'none')
    } finally {
      app.hideLoading()
    }
  },

  // 立即购买
  async onBuyNow() {
    if (!app.globalData.token) {
      this.showLoginModal()
      return
    }

    const { product, selectedSpec, quantity } = this.data

    // 检查库存
    const maxStock = this.getMaxStock()
    if (maxStock <= 0) {
      app.showToast('商品已售罄', 'none')
      return
    }

    if (quantity > maxStock) {
      app.showToast('库存不足', 'none')
      return
    }

    // 先加入购物车，然后跳转到订单页面
    app.showLoading('处理中...')

    try {
      const response = await app.request({
        url: '/orders/cart/',
        method: 'POST',
        data: {
          flower: product.id,
          flower_spec: selectedSpec ? selectedSpec.id : null,
          quantity
        }
      })

      if (response.success) {
        // 跳转到订单确认页面
        wx.navigateTo({
          url: `/pages/order/order?cartIds=${response.data.id}&direct=1`
        })
      } else {
        app.showToast(response.message || '操作失败', 'none')
      }
    } catch (error) {
      console.error('立即购买失败:', error)
      app.showToast('操作失败，请重试', 'none')
    } finally {
      app.hideLoading()
    }
  },

  // 显示登录弹窗
  showLoginModal() {
    wx.showModal({
      title: '提示',
      content: '请先登录后再操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 显示购物车提示
  showCartTip() {
    wx.showModal({
      title: '添加成功',
      content: '商品已加入购物车，是否立即查看？',
      confirmText: '查看购物车',
      cancelText: '继续购物',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/cart/cart'
          })
        }
      }
    })
  }
})